package com.zzs.elm.framework;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Arrays;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zzs.elm.util.MyJSONUtil;

@WebServlet("/")
public class DispatcherServlet extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static String PROFIX = "com.zzs.elm.controller.";
	private static String ROOT = "/elm";

	private void allRequest (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json;charset=utf-8");
		
		String path = req.getServletPath();
		System.out.println("[elm-log] path:" + path);
		String[] classAndMethod = path.split("[/]");
		System.out.println(Arrays.asList(classAndMethod));
		PrintWriter pw = resp.getWriter();
		try {
			if (classAndMethod.length <= 0/* || classAndMethod == null*/ || classAndMethod[1].equals(ROOT))
				return;
			Class<?> clazz = Class.forName(PROFIX  + classAndMethod[1]);
			Object controller = clazz.newInstance();
			Method method = clazz.getMethod(classAndMethod[2], HttpServletRequest.class);
			Object result = method.invoke(controller, req);
			String log = MyJSONUtil.ok(result);
			pw.print(log);
			System.out.println("[elm-log] result: " + log);
		} catch (Exception e) {
			pw.print(MyJSONUtil.bad());
			e.printStackTrace();
		} finally {
			pw.close();
		}
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		allRequest(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		allRequest(req, resp);
	}

}
